package com.kedacom.demo.spring.websocket;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * AbstractWebSocketServerHandler
 * @author luocanfeng
 * @date 2017年8月11日
 */
public abstract class AbstractWebSocketServerHandler extends TextWebSocketHandler {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected static List<WebSocketSession> sessions = new ArrayList<WebSocketSession>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		sessions.add(session);
		logger.info("有新连接加入，session id：{}，当前在线人数为：{}", session.getId(), sessions.size());
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String text = message.getPayload();
		logger.info("收到来自客户端（{}）的消息：{}", session.getId(), text);
	}

	@Override
	protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
		logger.error("不支持二进制消息，请发字符串文本消息！");
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable e) throws Exception {
		logger.error("传输错误：{}", e.getMessage());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		sessions.remove(session);
		logger.info("有连接关闭，session id：{}，close status：[code: {}, reason: {}]，当前在线人数为：{}", session.getId(),
				status.getCode(), status.getReason(), sessions.size());
	}

}
